<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * 首页接口
 */
class Component extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 组件分类
     *
     */
    public function componentClass()
    {
        $componentClassList = DB::table('fa_component_type')->select();

        
        $this->success('请求成功',$componentClassList);
    }

    /**
     * 网址分类
     *
     */
    public function websiteClass()
    {
        $websiteClassList = DB::table('fa_website_type')->select();

        
        $this->success('请求成功',$websiteClassList);
    }

    /**
     * 网址组件
     *
     */
    public function websiteList()
    {
        $websiteList = DB::table('fa_website')->select();
        // $websiteList = '111';
        
        $this->success('111',$websiteList);
    }




    /**
     * 邮箱服务器封装调用
     */
    public function initMailer(){
        $mail = new PHPMailer(true);
        try {
            // 服务器设置
            $mail->SMTPDebug = 0;                          // 启用详细调试输出
            $mail->isSMTP();                              // 设置邮件客户端以使用SMTP
            $mail->Host       = 'smtp.163.com';       // 指定主要SMTP服务器
            $mail->SMTPAuth   = true;                     // 启用SMTP认证
            $mail->Username   = 'dhzhuanhao@163.com'; // SMTP用户名
            $mail->Password   = 'DTir8qyUz6hGvqgA';    // SMTP密码       
            $mail->SMTPSecure = 'ssl';                    // 启用TLS加密，`ssl`也被接受
            $mail->Port       = 465;                      // TCP端口号
            
            // 收发件人设置可以在发送邮件时动态指定
            
            return $mail;
        } catch (Exception $e) {
            // 处理异常
            return null;
        }
    }



    /**
     * 发送邮箱验证码
     */
    public function sendVerificationCode() {
        $userEmail = input('post.email'); // 获取用户输入的邮箱地址
       
        // 生成验证码
        $verificationCode = rand(100000, 999999);
        
        // 保存验证码（这里以会话为例）
        session('verification_code_' . md5($userEmail), $verificationCode);
        session('verification_code_time_' . md5($userEmail), time()); // 可选：记录发送时间，用于设置验证码有效期
        
        // 配置并发送邮件
        $mail = $this->initMailer();
        $mail->setFrom('dhzhuanhao@163.com');
        $mail->addAddress($userEmail);
        $mail->isHTML(false);
        $mail->Subject = $verificationCode;
        $mail->Body    = "您的验证码是: " . $verificationCode;
        
        if ($mail->send()) {
            $this->success('邮箱验证码发送成功',$verificationCode);
            // return json(['status' => 'success', 'message' => 'Verification code sent to your email.']);
        } else {
            $this->success('邮箱验证码发送失败');
            // return json(['status' => 'error', 'message' => 'Failed to send verification code.']);
        }
    }





    /**
     * 校验邮箱验证码
     */
    public function verifyCode() {
        $userEmail = input('post.email');
        $userCode = input('post.code');
        
        // 从会话中获取保存的验证码
        $savedCode = session('verification_code_' . md5($userEmail));
        $codeTime = session('verification_code_time_' . md5($userEmail)); // 可选：获取发送时间
       
        if ($savedCode && $savedCode == $userCode) {
            $uid = DB::table('fa_tab_user')->where('email',$userEmail)->field('uid')->find();
            if(empty($userlist)){
                $uid = Db::table('fa_tab_user')->insertGetId(['email'=>$userEmail,'createdate'=>date('Y-m-d H:i:s')]);
            }
         
            //清除会话中的验证码（可选：也可以设置登录后自动清除）
            session(null, 'verification_code_' . md5($userEmail));
            session(null, 'verification_code_time_' . md5($userEmail));
            
            $this->success('验证成功',$uid);
        } else {
            // 验证码错误或已过期
            $this->success('验证失败');
        }
    }




    /**
     * 获取网站icon接口
     */
    public function getWebIcon(){
        $url = input('post.url');
        $apiUrl = "https://api.website-metadata.org/api/favicon?url=" . urlencode($url);
        $response = file_get_contents($apiUrl);
    
        if ($response === FALSE) {
            return FALSE; // 无法获取API响应
        }
    
        $data = json_decode($response, true);
    
        if (isset($data['favicon_url'])) {
            return $data['favicon_url'];
        } else {
            return FALSE; // 未找到favicon
        }
    }
}
